package org.hncors.gnssparse.fragement;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;


import com.southgnss.connect.DeviceParManage;
import com.southgnss.connect.SateEnableEvent;
import com.southgnss.connect.TopDeviceManage;
import com.southgnss.gnssparse.GnssSateInfo;
import com.southgnss.gnssparse.GnssSateStatus;
import com.southgnss.gnssparse.GnssSateSysType;
import com.southgnss.location.DateUtil;

import org.hncors.gnssparse.GnssSatelliteInfoView;
import org.hncors.gnssparse.R;
import org.hncors.gnssparse.SatellitesViewActivity;
import org.hncors.gnssparse.base.BaseFragment;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;


public class GnssMapFragment extends BaseFragment implements View.OnClickListener {
    private View view;
    TextView tv_gps_num_value;
    //  TextView tv_gps_state_value;
    //   TextView tv_wgs84_lat_value;
    //   TextView tv_wgs84_long_value;
    //  TextView tv_wgs84_height_value;
    TextView tv_wgs84_time_value;
    GnssSatelliteInfoView satellitesView;
    private Button gpsButton;
    private Button sbasButton;
    private Button gpsANDsbasButton;
    private DeviceParManage dPM;
    private Handler handler;
    private ArrayList<GnssSateInfo> mgpsSatsList;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        //定义了一个地图view
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(view == null){
            view = super.onCreateView(inflater,container,savedInstanceState);
            appendTopBody(R.layout.activity_top_icon);
            appendMainBody(this, R.layout.activity_gps_view2);
            setTopBarTitle("星图");
            EventBus.getDefault().register(this);

        }
        initView();
        return view;
    }
    private void initView(){
        handler = new Handler();
        dPM = DeviceParManage.GetInstance();

        tv_gps_num_value = (TextView) view.findViewById(R.id.tv_gps_num_value);
        tv_wgs84_time_value = (TextView) view.findViewById(R.id.tv_wgs84_time_value);
        satellitesView = (GnssSatelliteInfoView) view.findViewById(R.id.satellitesView);

        view.findViewById(R.id.buttonAll).setOnClickListener(this);
        gpsButton = (Button) view.findViewById(R.id.buttonGps);
        sbasButton = (Button) view.findViewById(R.id.buttonbeidou);
        gpsANDsbasButton = (Button) view.findViewById(R.id.buttonGpsAndbeidou);
        if (gpsButton != null) gpsButton.setOnClickListener(this);
        if (sbasButton != null) sbasButton.setOnClickListener(this);
        if (gpsANDsbasButton != null) gpsANDsbasButton.setOnClickListener(this);
//        GpsAnalysis.getInstance().addLocationDataChangeListener(this);
        handler.postDelayed(runnable,1000);
    }
    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onDestroy() {
        handler.removeCallbacks(runnable);
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    Runnable runnable = new Runnable() {
        @Override
        public void run() {
//            tv_wgs84_long_value.setText(StingUtils.strRAD2String(TopDeviceManage.getInstance(null)
//                    .getLongitude() * Math.PI / 180, 5, 2));
//            tv_wgs84_lat_value.setText(StingUtils.strRAD2String(TopDeviceManage.getInstance(null).getLatitude() * Math.PI / 180, 5, 1));
//            tv_wgs84_height_value.setText(String.format("%.4f", TopDeviceManage.getInstance(null).getAltitude()));

            tv_gps_num_value.setText(String.valueOf(String.format("%d/%d",
                    TopDeviceManage.getInstance(null).getSatInLock(), TopDeviceManage.getInstance(null).getSateSysListt()!= null ? TopDeviceManage.getInstance(null).getSateSysListt().length : 0)));

            tv_wgs84_time_value.setText(DateUtil.formatDate(new Date(TopDeviceManage.getInstance(null).getLocalTime()), "HH:mm:ss"));
            switch (TopDeviceManage.getInstance(null).getStatusType()) {
                case 0:
//                    tv_gps_state_value
//                            .setText(getString(R.string.gps_plot_state_search_satellite));
                    break;
                case 1:
//                    tv_gps_state_value
//                            .setText(getString(R.string.gps_plot_state_point));
                    break;
                case 2:
//                    tv_gps_state_value
//                            .setText(getString(R.string.gps_plot_state_differential));
                    break;
                case 3:
//                    tv_gps_state_value
//                            .setText(getString(R.string.gps_plot_state_float));
                    break;
                case 4:
//                    tv_gps_state_value
//                            .setText(getString(R.string.gps_plot_state_fixed));
                    break;
                case 5:
//                    tv_gps_state_value
//                            .setText(getString(R.string.gps_plot_state_float));
                    break;
                default:
//                    tv_gps_state_value
//                            .setText(getString(R.string.gps_plot_state_search_satellite));
                    break;
            }

            /** 获取卫星状态信息*/
            getStatusChanged();

            handler.postDelayed(runnable,1000);
        }
    };

    private void getStatusChanged() {
        try {
            TopDeviceManage extras = TopDeviceManage.getInstance(mActivity);
            int iSatInView = extras.getSatInView();
            if (mgpsSatsList == null) {
                mgpsSatsList = new ArrayList<GnssSateInfo>();
            }

            boolean bSerialport = false;
            GnssSateInfo temSatellite = null;
            mgpsSatsList.clear();
            if (iSatInView > 0) {
                int[] PrnList = extras.getPrnList();
                float[] AzimuthList = extras.getAzimuthList();
                float[] ElevationList = extras.getElevationList();
                float[] Snr1List = extras.getSnr1List();
                float[] Snr2List = extras.getSnr2List();
                float[] Snr3List = extras.getSnr3List();
                int[] StatusList = extras.getStatusList();
                int[] SateSysList = extras.getSateSysListt();
                //}

                int nSnr = -1;
                for (int i = 0; i < iSatInView; i++) {
                    temSatellite = new GnssSateInfo();
                    temSatellite.setPrn(PrnList[i]);
                    temSatellite.setAzimuth((int) AzimuthList[i]);
                    temSatellite.setElevation((int) ElevationList[i]);
                    temSatellite.setSnr1(Snr1List[i]);
                    temSatellite.setSnr2(Snr2List[i]);
                    temSatellite.setSnr3(Snr3List[i]);
                    temSatellite.setStatus(GnssSateStatus.swigToEnum(StatusList[i]));
                    if (bSerialport) {
                        nSnr = (int) temSatellite.getPrn();
                        if (nSnr >= 1 && nSnr <= 32) {
                            temSatellite.setType(GnssSateSysType.SATSYS_GPS);
                        } else if (nSnr >= 120 && nSnr <= 140) {
                            temSatellite.setType(GnssSateSysType.SATSYS_SBAS);
                        } else if (nSnr >= 38 && nSnr <= 69) {
                            temSatellite.setType(GnssSateSysType.SATSYS_GLONASS);
                        } else if (nSnr >= 161 && nSnr <= 198) {
                            temSatellite.setType(GnssSateSysType.SATSYS_BD);
                        } else {
                            temSatellite.setType(GnssSateSysType.SATSYS_NULL);
                        }
                    } else {
                        temSatellite.setType(GnssSateSysType.swigToEnum(SateSysList[i]));
                    }
                    mgpsSatsList.add(temSatellite);
                }
            }
            //排序
            Comparator comparator = new MyComparator();//重要部分
            Collections.sort(mgpsSatsList, comparator);

            satellitesView.setGpsSatellitesList(mgpsSatsList);
        } catch (Exception e) {

        }
    }

    private class MyComparator implements Comparator<GnssSateInfo> {

        public int compare(GnssSateInfo s1, GnssSateInfo s2) {
            if(s1.getPrn() > s2.getPrn()){
                return 1;
            } else if(s1.getPrn() < s2.getPrn()) {
                return -1;
            }
            return 0;
        }
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.buttonGps) {
            //单GPS切换，其他卫星关闭，成功后eventbus返回消息
            dPM.SetSatelliteEnableGps(true);
            dPM.SetSatelliteEnableBds(false);
            dPM.SetSatelliteEnableGalileo(false);
            dPM.SetSatelliteEnableGlonass(false);
            dPM.SetSatelliteEnableQzss(false);
            dPM.SetSatelliteEnableSbas(false);
        } else if (view.getId() == R.id.buttonbeidou) {
            //单北斗切换，其他卫星关闭，成功后eventbus返回消息
            dPM.SetSatelliteEnableBds(true);
            dPM.SetSatelliteEnableSbas(false);
            dPM.SetSatelliteEnableGps(false);
            dPM.SetSatelliteEnableGalileo(false);
            dPM.SetSatelliteEnableGlonass(false);
            dPM.SetSatelliteEnableQzss(false);
        } else if (view.getId() == R.id.buttonGpsAndbeidou) {
            //两者（GPS，北斗）混合定位切换，其他卫星关闭，成功后eventbus返回消息
            dPM.SetSatelliteEnableGps(true);
            dPM.SetSatelliteEnableBds(true);
            dPM.SetSatelliteEnableSbas(false);
            dPM.SetSatelliteEnableGalileo(false);
            dPM.SetSatelliteEnableGlonass(false);
            dPM.SetSatelliteEnableQzss(false);
        } else if(view.getId() == R.id.buttonAll){
            dPM.SetSatelliteEnableGps(true);
            dPM.SetSatelliteEnableBds(true);
            dPM.SetSatelliteEnableSbas(true);
            dPM.SetSatelliteEnableGalileo(true);
            dPM.SetSatelliteEnableGlonass(true);
            dPM.SetSatelliteEnableQzss(true);
        }
    }


    //单GPS切换返回消息
    public void onEventMainThread(SateEnableEvent.DeviceSatelliteEnableGpsEvent obj) {
        if (obj == null) return;
        if (obj.getStatus() == true) {
            Toast.makeText(mActivity, getString(R.string.setting_rtk_net_setting_success), Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(mActivity, getString(R.string.setting_rtk_net_setting_failed), Toast.LENGTH_SHORT).show();
        }
    }
    //单北斗切换返回消息
    public void onEventMainThread(SateEnableEvent.DeviceSatelliteEnableBdsEvent obj) {
        if (obj == null) return;
        if (obj.getStatus() == true) {
            Toast.makeText(mActivity, getString(R.string.setting_rtk_net_setting_success), Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(mActivity, getString(R.string.setting_rtk_net_setting_failed), Toast.LENGTH_SHORT).show();
        }
    }
}
